﻿#region Disclaimer/License Info

/* *********************************************** */

// sBlog.Net

// sBlog.Net is a minimalistic blog engine software.

// Homepage: http://sblogproject.net
// Github: http://github.com/karthik25/sBlog.Net

// This project is licensed under the BSD license.  
// See the License.txt file for more information.

/* *********************************************** */

#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using MemcachedProviders.Cache;
using sBlog.Net.Areas.Admin.Models;
using sBlog.Net.Common;
using sBlog.Net.Domain.Concrete;
using sBlog.Net.Domain.Entities;
using sBlog.Net.Domain.Interfaces;
using sBlog.Net.Enumerations;
using sBlog.Net.FluentExtensions;
using sBlog.Net.Infrastructure;
using sBlog.Net.Models;

namespace sBlog.Net.Areas.Admin.Controllers
{
    public class PostController : Controller
    {
        private readonly IPost _postRepository;
        private readonly ICategory _categoryRepository;
        private readonly ITag _tagRepository;
        private const byte ItemEntryType = 1;
        private static bool EditStatus = false;//True = Edit; False = AddNew
        private static string ImgFolder = string.Empty;

        public PostController(IPost postRepository, ICategory categoryRepository, ITag tagRepository)
        {
            _postRepository = postRepository;
            _categoryRepository = categoryRepository;
            _tagRepository = tagRepository;
        }

        protected int GetUserId()
        {
            var userId = -1;
            if (Request.IsAuthenticated)
            {
                var userIdentity = (IUserInfo)User.Identity;
                userId = Int32.Parse(userIdentity.UserId);
            }
            return userId;
        }

        protected string GetToken()
        {
            var userIdentity = (UserIdentity)User.Identity;
            return userIdentity.UserToken;
        }

        public ActionResult Add()
        {
            ViewData["Hour"] = "08";
            ViewData["Minute"] = "00";
            //ViewData["Folder"] = DateTime.Now.Year.ToString("d4") + DateTime.Now.Month.ToString("d2");
            var postModel = new PostViewModel
                                {
                                    Post = new PostEntity { EntryType = ItemEntryType, UserCanAddComments = true, CanBeShared = true, PublicDate = DateTime.Now },
                                    Categories = GetModel(_categoryRepository.GetCategories()),
                                    Tags = string.Empty,
                                    Title = "Mlog",
                                    SharingEnabled = false
                                };

            EditStatus = false;
            ImgFolder = string.Empty;

            GetListZone();
            GetListCatByZone();
            MchoiceList();

            return View(postModel);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Add(PostViewModel postModel, string txtHour, string txtMinute, string FolderImage)
        {
            if (ModelState.IsValid)
            {
                var tags = _tagRepository.GetTagEntities(postModel.Tags.Split(',').ToList());
                _tagRepository.AddTags(tags);
                var postEntity = postModel.ToPostEntity(_tagRepository);
                postEntity.PostAddedDate = DateTime.Now;
                postEntity.PostEditedDate = postEntity.PostAddedDate;
                postEntity.OwnerUserID = GetUserId();
                postEntity.LikeCount = 0;
                postEntity.ViewCount = 0;
                postEntity.Status = 0;

                if (!string.IsNullOrEmpty(FolderImage))
                {
                    postEntity.Folder = FolderImage;
                }

                if (Roles.IsUserInRole("SuperAdmin") || Roles.IsUserInRole("Admin"))
                {
                    if (txtHour == "")
                    {
                        txtHour = "12";
                    }
                    if (txtMinute == "")
                    {
                        txtMinute = "00";
                    }

                    DateTime dtime = new DateTime(Convert.ToInt32(postEntity.PublicDate.Year), Convert.ToInt32(postEntity.PublicDate.Month), Convert.ToInt32(postEntity.PublicDate.Day), Convert.ToInt32(txtHour), Convert.ToInt32(txtMinute), 0);
                    postEntity.PublicDate = dtime;
                }
                else
                {
                    postEntity.PublicDate = DateTime.Now;
                    postEntity.Promote = false;
                    postEntity.OrderNumber = -1;
                    postEntity.PromoteType = -1;
                    postEntity.IsPrivate = true;
                }

                if (string.IsNullOrEmpty(postEntity.PostUrl))
                {
                    postEntity.PostUrl = UniqueUrlHelper.FindUniqueUrl(_postRepository, postEntity.PostTitle, ItemEntryType);
                }

                var postID = _postRepository.AddPost(postEntity);

                if (postID > 0)
                {
                    return RedirectToAction("Edit", new { postID, newlyAdded = true });
                }
            }

            postModel.Title = "Mlog";
            postModel.SharingEnabled = false;

            DistCache.Remove(MemCacheKey.KeyGetPostByUrl + postModel.Post.PostUrl);
            DistCache.Remove(MemCacheKey.KeyGetPostByID + postModel.Post.PostID);
            DistCache.Remove(MemCacheKey.KeyGetNewPosts);

            EditStatus = false;
            ImgFolder = string.Empty;

            GetListZone();
            GetListCatByZone();
            MchoiceList();

            return View(postModel);
        }

        public ActionResult Edit(int postID, [DefaultValue(false)] bool newlyAdded)
        {
            GetListZone();
            GetListCatByZone();
            MchoiceList();

            var post = _postRepository.GetPostByID(postID);
            if (post != null)
            {
                post.Categories = _categoryRepository.GetCategoriesByPostID(post.PostID);
            }

            ValidateEditRequest(post);

            ViewData["Folder"] = post.Folder;
            ViewData["PostAvatar"] = post.PostAvatar;
            ViewData["PostAvatarFeature"] = post.PostAvatarFeature;
            ViewData["PostAvatarSquare"] = post.PostAvatarSquare;
            ViewData["PostAvatarYanNews"] = post.PostAvatarYanNews;

            ViewData["VideoUrl"] = post.VideoUrl;
            ViewData["Hour"] = post.PublicDate.Hour;
            ViewData["Minute"] = post.PublicDate.Minute;
            var postModel = new PostViewModel
                                {
                                    Post = post,
                                    Categories = GetModel(_categoryRepository.GetCategories(), post.Categories),
                                    Tags =
                                        string.Join(",",
                                                    _tagRepository.GetTagsByPostID(postID).Select(t => t.TagName).
                                                        ToArray()),
                                    Title = "Mlog",
                                    SharingEnabled = false
                                };

            EditStatus = true;
            ImgFolder = postModel.Post.PostYear + postModel.Post.PostMonth;

            if (newlyAdded)
            {
                postModel.UpdateStatus = true;
                postModel.IsNewPostOrPage = true;
            }

            return View(postModel);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(PostViewModel postModel, string txtHour, string txtMinute, string FolderImage)
        {
            if (ModelState.IsValid)
            {
                var tags = _tagRepository.GetTagEntities(postModel.Tags.Split(',').ToList());
                _tagRepository.AddTags(tags);
                var postEntity = postModel.ToPostEntity(_tagRepository);
                postEntity.PostEditedDate = DateTime.Now;

                if (!string.IsNullOrEmpty(FolderImage))
                {
                    postEntity.Folder = FolderImage;
                }

                if (Roles.IsUserInRole("SuperAdmin") || Roles.IsUserInRole("Admin"))
                {
                    if (txtHour == "")
                    {
                        txtHour = "12";
                    }
                    if (txtMinute == "")
                    {
                        txtMinute = "00";
                    }

                    DateTime dtime = new DateTime(Convert.ToInt32(postEntity.PublicDate.Year), Convert.ToInt32(postEntity.PublicDate.Month), Convert.ToInt32(postEntity.PublicDate.Day), Convert.ToInt32(txtHour), Convert.ToInt32(txtMinute), 0);
                    postEntity.PublicDate = dtime;
                }

                if (string.IsNullOrEmpty(postEntity.PostUrl))
                {
                    postEntity.PostUrl = UniqueUrlHelper.FindUniqueUrl(_postRepository, postEntity.PostTitle, ItemEntryType, postEntity.PostID);
                }

                _postRepository.UpdatePost(postEntity);

                postModel.UpdateStatus = true;
                postModel.IsNewPostOrPage = false;
            }

            postModel.Title = "Mlog";
            postModel.SharingEnabled = false;

            ViewData["PostAvatar"] = postModel.Post.PostAvatar;
            ViewData["PostAvatarFeature"] = postModel.Post.PostAvatarFeature;
            ViewData["PostAvatarSquare"] = postModel.Post.PostAvatarSquare;
            ViewData["PostAvatarYanNews"] = postModel.Post.PostAvatarYanNews;

            ViewData["VideoUrl"] = postModel.Post.VideoUrl;
            ViewData["Hour"] = postModel.Post.PublicDate.Hour;
            ViewData["Minute"] = postModel.Post.PublicDate.Minute;

            DistCache.Remove(MemCacheKey.KeyGetPostByUrl + postModel.Post.PostUrl);
            DistCache.Remove(MemCacheKey.KeyGetPostByID + postModel.Post.PostID);
            DistCache.Remove(MemCacheKey.KeyViewPostOrPageModel + postModel.Post.PostID);
            DistCache.Remove(MemCacheKey.KeyGetPostFeature);
            DistCache.Remove(MemCacheKey.KeyGetNewPosts);
            DistCache.Remove(MemCacheKey.KeyGetMostViewPostByCatSlug + "hinh-anh");
            DistCache.Remove(MemCacheKey.KeyGetMostViewPostByCatSlug + "video");
            DistCache.Remove(MemCacheKey.KeyGetMostViewPostByCatSlug + "bai-viet");

            GetListZone();
            GetListCatByZone();
            MchoiceList();

            EditStatus = false;

            return View(postModel);
        }

        public JsonResult Delete(int postID)
        {
            VerifyOwnership(postID);

            if (postID > 0)
            {
                _postRepository.DeletePost(postID);
                DistCache.Remove(MemCacheKey.KeyGetPostByID + postID);
            }

            DistCache.Remove(MemCacheKey.KeyGetPostFeature);
            DistCache.Remove(MemCacheKey.KeyGetNewPosts);
            DistCache.Remove(MemCacheKey.KeyGetMostViewPostByCatSlug + "hinh-anh");
            DistCache.Remove(MemCacheKey.KeyGetMostViewPostByCatSlug + "video");
            DistCache.Remove(MemCacheKey.KeyGetMostViewPostByCatSlug + "bai-viet");

            return Json(true, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DeletePost(int postID)
        {
            VerifyOwnership(postID);

            if (postID > 0)
            {
                _postRepository.DeletePost(postID);
                DistCache.Remove(MemCacheKey.KeyGetPostByID + postID);
            }

            DistCache.Remove(MemCacheKey.KeyGetPostFeature);
            DistCache.Remove(MemCacheKey.KeyGetNewPosts);
            DistCache.Remove(MemCacheKey.KeyGetMostViewPostByCatSlug + "hinh-anh");
            DistCache.Remove(MemCacheKey.KeyGetMostViewPostByCatSlug + "video");
            DistCache.Remove(MemCacheKey.KeyGetMostViewPostByCatSlug + "bai-viet");

            return RedirectToRoute("AdminPostsAdd");
        }

        public ActionResult ManagePosts([DefaultValue(1)] int page, string type)
        {
            var status = type != null ? (int)Enum.Parse(typeof(PostStatus), type, true) : 0;

            int lUserID;
            if (Roles.IsUserInRole("SuperAdmin") || Roles.IsUserInRole("Admin"))
            {
                lUserID = 0;
            }
            else
            {
                lUserID = GetUserId();
            }

            var allPostsByStatus = _postRepository.GetPostsByUserIDAndStatusForCPNew(lUserID, status, ItemEntryType, page);

            var postModel = new AdminPostOrPageViewModel
            {
                //Posts = allPostsByStatus.Skip((page - 1) * _itemsPerPage).Take(_itemsPerPage).ToList(),
                Posts = _postRepository.GetPostsByUserIDAndStatusForCPNew(lUserID, status, ItemEntryType, page),
                PagingInfo = new PagingInformation
                {
                    CurrentPage = page,
                    ItemsPerPage = 15,
                    //ItemsPerPage = _itemsPerPage,
                    TotalItems = 500
                    //TotalItems = allPostsByStatus.Count
                },
                Type = type,
                OneTimeCode = GetToken(),
                Title = "Mlog"
            };
            return View(postModel);
        }

        [HttpPost]
        public ActionResult ManagePosts(string txtSearch)
        {
            var allPostsByStatus = _postRepository.SearchKeywordWithPage(txtSearch, 1, 100);
            var postModel = new AdminPostOrPageViewModel
            {
                Posts = allPostsByStatus.ToList(),
                PagingInfo = new PagingInformation
                {
                    CurrentPage = 1,
                    ItemsPerPage = 100,
                    TotalItems = allPostsByStatus.Count
                },
                OneTimeCode = GetToken(),
                Title = "Mlog"
            };
            return View(postModel);
        }

        [HttpGet]
        public JsonResult VerifyUrlUrlExists(string postTitle, string entryType, int postId)
        {
            var post = postId > 0 ? _postRepository.GetPostByID(postId) : null;

            var finalUrl = post != null ? UniqueUrlHelper.FindUniqueUrl(_postRepository, postTitle, byte.Parse(entryType), postId)
                                           : UniqueUrlHelper.FindUniqueUrl(_postRepository, postTitle, byte.Parse(entryType));

            return Json(finalUrl, JsonRequestBehavior.AllowGet);
        }

        private void ValidateEditRequest(PostEntity postEntity)
        {
            if (postEntity.IsPrivate)
            {
                if (!Roles.IsUserInRole("SuperAdmin") && !Roles.IsUserInRole("Admin"))
                {
                    if (postEntity.OwnerUserID != GetUserId())
                    {
                        throw new UnauthorizedAccessException("Unauthorized attempt to edit the post");
                    }
                }
            }
            else
            {
                if (postEntity.OwnerUserID != GetUserId() && !User.IsInRole("SuperAdmin") && !Roles.IsUserInRole("Admin"))
                {
                    throw new UnauthorizedAccessException("Unauthorized attempt to edit the post");
                }
            }
        }

        private void VerifyOwnership(int postID)
        {
            var post = _postRepository.GetPostByID(postID);
            var userId = GetUserId();

            if (post.OwnerUserID != userId && userId != 1)
            {
                throw new UnauthorizedAccessException("An unauthroized access was detected");
            }
        }

        private static CheckBoxListViewModel GetModel(List<CategoryEntity> baseList, IEnumerable<CategoryEntity> selectedCategories = null)
        {
            var model = new CheckBoxListViewModel { HeaderText = "select categories" };
            var checkItems = new List<CheckBoxListItem>();
            baseList.ForEach(category =>
            {
                var item = new CheckBoxListItem
                {
                    Text = category.CategoryName,
                    Value = category.CategoryID.ToString(),
                    IsChecked = selectedCategories != null && selectedCategories.Any(c => c.CategoryID == category.CategoryID)
                };
                checkItems.Add(item);
            });

            if (selectedCategories == null)
            {
                var general = checkItems.SingleOrDefault(c => c.Text == "General");
                if (general != null)
                {
                    general.IsChecked = true;
                }
            }

            model.Items = checkItems;
            return model;
        }

        private void MchoiceList()
        {
            List<SelectListItem> mChoiceList = new List<SelectListItem>();
            mChoiceList.Add(new SelectListItem { Text = "--- Không chọn ---", Value = "0" });
            mChoiceList.Add(new SelectListItem { Text = "Sách hay", Value = "1" });
            mChoiceList.Add(new SelectListItem { Text = "Phim hay", Value = "2" });
            mChoiceList.Add(new SelectListItem { Text = "Bộ ảnh đẹp", Value = "3" });
            mChoiceList.Add(new SelectListItem { Text = "Câu nói hay", Value = "4" });
            ViewBag.lstMChoice = mChoiceList;
        }

        public void GetListZone(object obj = null)
        {
            var lst = DBFunction.ZoneGetList().ToList();
            ZoneEntity tbl = new ZoneEntity { ZoneId = -1, ZoneName = "Chọn chuyên mục" };
            lst.Insert(0, tbl);
            ViewBag.lstZone = new SelectList(lst, "ZoneId", "ZoneName", obj);
        }

        public void GetListCatByZone(object obj = null)
        {
            var lst = DBFunction.ZoneCategoriesByZone(0).ToList();
            CategoriesZoneEntity tbl = new CategoriesZoneEntity { CatId = -1, CatName = "Chọn chuyên mục con" };
            lst.Insert(0, tbl);
            ViewBag.lstCateZone = new SelectList(lst, "CatId", "CatName", obj);
        }

        public JsonResult CatType_SelectedState(string id)
        {
            int cid = int.Parse(id);
            JsonResult result = new JsonResult();
            result.Data = GetSubbuttonsSelectListItem(cid);
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

        private List<SelectListItem> GetSubbuttonsSelectListItem(int cat_type_id)
        {
            var lst = (from p in DBFunction.ZoneCategoriesByZone(cat_type_id)
                       select new SelectListItem
                       {
                           Text = p.CatName,
                           Value = p.CatId.ToString()
                       }).ToList();
            return lst;
        }

        #region Upload Function
        public string UploadAvatar(HttpPostedFileBase fileData)
        {
            Byte[] buffer = new Byte[1];

            string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString();
            string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString();
            string httpServer = System.Configuration.ConfigurationManager.AppSettings["HttpServer"].ToString();

            string ftpUploadUrl = string.Empty;
            string strFtpAddress = System.Configuration.ConfigurationManager.AppSettings["ftpServer"].ToString() + "Mlog/UploadThumbs/";

            string imgUrl = string.Empty;
            string strName = string.Empty;
            string folderName = string.Empty;
            try
            {
                folderName = DateTime.Now.Year.ToString("d4") + DateTime.Now.Month.ToString("d2");

                imgUrl = httpServer + "Mlog/UploadThumbs/" + folderName;

                //Create Folder
                ImageUtility.FtpCreateFolder(strFtpAddress + folderName, strUserNameFtp, strPassFtp);

                strFtpAddress = strFtpAddress + folderName;

                strName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);

                ////////
                Bitmap bmp = new Bitmap(fileData.InputStream);
                buffer = ImageUtility.SaveImage(bmp, 100L);
                ftpUploadUrl = strFtpAddress + "/" + strName;
                ImageUtility.UpFileServer(ftpUploadUrl, buffer);
                bmp.Dispose();
                ////////

                /////////////
                /////////////
                /////////////
                #region New Layout
                ////////660x380
                Bitmap bmp660 = new Bitmap(fileData.InputStream);
                if (bmp660.Width > 660 || bmp660.Height > 380)
                {
                    Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp660, new Rectangle(0, 0, 660, 380));
                    buffer = ImageUtility.SaveImage(bmpResize, 100L);
                    bmp660.Dispose();
                    bmpResize.Dispose();
                }
                else buffer = ImageUtility.SaveImage(bmp660, 100L);
                ftpUploadUrl = strFtpAddress + "/660x380_" + strName;
                ImageUtility.UpFileServer(ftpUploadUrl, buffer);
                bmp660.Dispose();
                ////////

                ////////280x210
                Bitmap bmp280 = new Bitmap(fileData.InputStream);
                if (bmp280.Width > 280 || bmp280.Height > 210)
                {
                    Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp280, new Rectangle(0, 0, 280, 210));
                    buffer = ImageUtility.SaveImage(bmpResize, 100L);
                    bmp280.Dispose();
                    bmpResize.Dispose();
                }
                else buffer = ImageUtility.SaveImage(bmp280, 100L);
                ftpUploadUrl = strFtpAddress + "/280x210_" + strName;
                ImageUtility.UpFileServer(ftpUploadUrl, buffer);
                bmp280.Dispose();
                ////////
                #endregion End new layout
                /////////////
                /////////////
                /////////////

                ////////
                Bitmap bmp80 = new Bitmap(fileData.InputStream);
                if (bmp80.Width > 80 || bmp80.Height > 80)
                {
                    Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp80, new Rectangle(0, 0, 80, 80));
                    buffer = ImageUtility.SaveImage(bmpResize, 100L);
                    bmp80.Dispose();
                    bmpResize.Dispose();
                }
                else buffer = ImageUtility.SaveImage(bmp80, 100L);
                ftpUploadUrl = strFtpAddress + "/80x80_" + strName;
                ImageUtility.UpFileServer(ftpUploadUrl, buffer);
                bmp80.Dispose();
                ////////

                ////////
                Bitmap bmp110 = new Bitmap(fileData.InputStream);
                if (bmp110.Width > 110 || bmp110.Height > 120)
                {
                    Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp110, new Rectangle(0, 0, 110, 120));
                    buffer = ImageUtility.SaveImage(bmpResize, 100L);
                    bmp110.Dispose();
                    bmpResize.Dispose();
                }
                else buffer = ImageUtility.SaveImage(bmp110, 100L);
                ftpUploadUrl = strFtpAddress + "/110x120_" + strName;
                ImageUtility.UpFileServer(ftpUploadUrl, buffer);
                bmp110.Dispose();
                ////////

                ////////
                Bitmap bmp70 = new Bitmap(fileData.InputStream);
                if (bmp70.Width > 70 || bmp70.Height > 40)
                {
                    Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp70, new Rectangle(0, 0, 70, 44));
                    buffer = ImageUtility.SaveImage(bmpResize, 100L);
                    bmp70.Dispose();
                    bmpResize.Dispose();
                }
                else buffer = ImageUtility.SaveImage(bmp70, 100L);
                ftpUploadUrl = strFtpAddress + "/70x44_" + strName;
                ImageUtility.UpFileServer(ftpUploadUrl, buffer);
                bmp70.Dispose();
                ////////

                ////////
                Bitmap bmp196 = new Bitmap(fileData.InputStream);
                if (bmp196.Width > 196 || bmp196.Height > 196)
                {
                    Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp196, new Rectangle(0, 0, 196, 196));
                    buffer = ImageUtility.SaveImage(bmpResize, 100L);
                    bmp196.Dispose();
                    bmpResize.Dispose();
                }
                else buffer = ImageUtility.SaveImage(bmp196, 100L);
                ftpUploadUrl = strFtpAddress + "/196x196_" + strName;
                ImageUtility.UpFileServer(ftpUploadUrl, buffer);
                bmp196.Dispose();
                ////////
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            imgUrl = imgUrl + "/80x80_" + strName;

            return imgUrl;
        }

        public string UploadAvatarFeature(HttpPostedFileBase fileData)
        {
            Byte[] buffer = new Byte[1];

            string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString();
            string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString();
            string httpServer = System.Configuration.ConfigurationManager.AppSettings["HttpServer"].ToString();

            string ftpUploadUrl = string.Empty;
            string strFtpAddress = System.Configuration.ConfigurationManager.AppSettings["ftpServer"].ToString() + "Mlog/UploadThumbs/";

            string strName = string.Empty;
            string imgUrl = string.Empty;
            string folderName = string.Empty;

            try
            {
                if (EditStatus == false)
                {
                    folderName = DateTime.Now.Year.ToString("d4") + DateTime.Now.Month.ToString("d2");
                }
                else
                {
                    folderName = ImgFolder;
                }

                imgUrl = httpServer + "Mlog/UploadThumbs/" + folderName;
                //Create Folder
                ImageUtility.FtpCreateFolder(strFtpAddress + folderName, strUserNameFtp, strPassFtp);

                strFtpAddress = strFtpAddress + folderName;

                strName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);

                ////////
                Bitmap bmp990 = new Bitmap(fileData.InputStream);
                if (bmp990.Width > 990 || bmp990.Height > 392)
                {
                    Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp990, new Rectangle(0, 0, 990, 392));
                    buffer = ImageUtility.SaveImage(bmpResize, 100L);
                    bmp990.Dispose();
                    bmpResize.Dispose();
                }
                else buffer = ImageUtility.SaveImage(bmp990, 100L);
                ftpUploadUrl = strFtpAddress + "/990x392_" + strName;
                ImageUtility.UpFileServer(ftpUploadUrl, buffer);
                bmp990.Dispose();
                ////////

                ////////
                Bitmap bmp80 = new Bitmap(fileData.InputStream);
                if (bmp80.Width > 80 || bmp80.Height > 80)
                {
                    Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp80, new Rectangle(0, 0, 80, 80));
                    buffer = ImageUtility.SaveImage(bmpResize, 100L);
                    bmp80.Dispose();
                    bmpResize.Dispose();
                }
                else buffer = ImageUtility.SaveImage(bmp80, 100L);
                ftpUploadUrl = strFtpAddress + "/80x80_" + strName;
                ImageUtility.UpFileServer(ftpUploadUrl, buffer);
                bmp80.Dispose();
                ////////
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            imgUrl = imgUrl + "/80x80_" + strName;
            return imgUrl;
        }

        public string UploadAvatarYanNews(HttpPostedFileBase fileData)
        {
            Byte[] buffer = new Byte[1];

            string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString();
            string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString();
            string httpServer = System.Configuration.ConfigurationManager.AppSettings["HttpServer"].ToString();

            string ftpUploadUrl = string.Empty;
            string strFtpAddress = System.Configuration.ConfigurationManager.AppSettings["ftpServer"].ToString() + "Mlog/UploadThumbs/";

            string strName = string.Empty;
            string imgUrl = string.Empty;
            string folderName = string.Empty;

            try
            {
                if (EditStatus == false)
                {
                    folderName = DateTime.Now.Year.ToString("d4") + DateTime.Now.Month.ToString("d2");
                }
                else
                {
                    folderName = ImgFolder;
                }

                imgUrl = httpServer + "Mlog/UploadThumbs/" + folderName;

                //Create Folder
                ImageUtility.FtpCreateFolder(strFtpAddress + folderName, strUserNameFtp, strPassFtp);
                strFtpAddress = strFtpAddress + folderName;

                strName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);

                ////////
                Bitmap bmp550 = new Bitmap(fileData.InputStream);
                if (bmp550.Width > 550 || bmp550.Height > 275)
                {
                    Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp550, new Rectangle(0, 0, 550, 275));
                    buffer = ImageUtility.SaveImage(bmpResize, 100L);
                    bmp550.Dispose();
                    bmpResize.Dispose();
                }
                else buffer = ImageUtility.SaveImage(bmp550, 100L);
                ftpUploadUrl = strFtpAddress + "/550x275_" + strName;
                ImageUtility.UpFileServer(ftpUploadUrl, buffer);
                bmp550.Dispose();
                ////////

                ////////
                Bitmap bmp300 = new Bitmap(fileData.InputStream);
                if (bmp300.Width > 300 || bmp300.Height > 150)
                {
                    Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp300, new Rectangle(0, 0, 300, 150));
                    buffer = ImageUtility.SaveImage(bmpResize, 100L);
                    bmp300.Dispose();
                    bmpResize.Dispose();
                }
                else buffer = ImageUtility.SaveImage(bmp300, 100L);
                ftpUploadUrl = strFtpAddress + "/300x150_" + strName;
                ImageUtility.UpFileServer(ftpUploadUrl, buffer);
                bmp300.Dispose();
                ////////
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            imgUrl = imgUrl + "/300X150_" + strName;
            return imgUrl;
        }

        public string UploadAvatarSquare(HttpPostedFileBase fileData)
        {
            Byte[] buffer = new Byte[1];

            string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString();
            string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString();
            string httpServer = System.Configuration.ConfigurationManager.AppSettings["HttpServer"].ToString();

            string ftpUploadUrl = string.Empty;
            string strFtpAddress = System.Configuration.ConfigurationManager.AppSettings["ftpServer"].ToString() + "Mlog/UploadThumbs/";

            string strName = string.Empty;
            string imgUrl = string.Empty;
            string folderName = string.Empty;
            try
            {
                if (EditStatus == false)
                {
                    folderName = DateTime.Now.Year.ToString("d4") + DateTime.Now.Month.ToString("d2");
                }
                else
                {
                    folderName = ImgFolder;
                }

                imgUrl = httpServer + "Mlog/UploadThumbs/" + folderName;

                //Create Folder
                ImageUtility.FtpCreateFolder(strFtpAddress + folderName, strUserNameFtp, strPassFtp);

                strFtpAddress = strFtpAddress + folderName;

                strName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);

                ////////
                Bitmap bmp196 = new Bitmap(fileData.InputStream);
                if (bmp196.Width > 196 || bmp196.Height > 196)
                {
                    Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp196, new Rectangle(0, 0, 196, 196));
                    buffer = ImageUtility.SaveImage(bmpResize, 100L);
                    bmp196.Dispose();
                    bmpResize.Dispose();
                }
                else buffer = ImageUtility.SaveImage(bmp196, 100L);
                ftpUploadUrl = strFtpAddress + "/196x196_" + strName;
                ImageUtility.UpFileServer(ftpUploadUrl, buffer);
                bmp196.Dispose();
                ////////

                ////////
                Bitmap bmp80 = new Bitmap(fileData.InputStream);
                if (bmp80.Width > 80 || bmp80.Height > 80)
                {
                    Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp80, new Rectangle(0, 0, 80, 80));
                    buffer = ImageUtility.SaveImage(bmpResize, 100L);
                    bmp80.Dispose();
                    bmpResize.Dispose();
                }
                else buffer = ImageUtility.SaveImage(bmp80, 100L);
                ftpUploadUrl = strFtpAddress + "/80x80_" + strName;
                ImageUtility.UpFileServer(ftpUploadUrl, buffer);
                bmp80.Dispose();
                ////////
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            imgUrl = imgUrl + "/80x80_" + strName;
            return imgUrl;
        }

        //public string UploadVideo(HttpPostedFileBase fileData)
        //{
        //    string fName = Guid.NewGuid().ToString() + ".xyz";
        //    string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserNameVideo"].ToString();
        //    string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPasswordVideo"].ToString();
        //    string ftpServer = System.Configuration.ConfigurationManager.AppSettings["ftpServerVideo"].ToString();

        //    string strFtpAddress = ftpServer + "/MlogVideo";

        //    string strFolderUser = ImageUtility.GetFolderByDate(strFtpAddress);
        //    ImageUtility.FtpCreateFolder(strFolderUser, strUserNameFtp, strPassFtp);

        //    string ftpUploadUrl = strFolderUser + "/" + fName;
        //    ImageUtility.UploadVideoClip(ftpUploadUrl, fileData, fName, strUserNameFtp, strPassFtp);
        //    fName = fName.Replace("xyz", "mp4");
        //    string strDate = DateTime.Now.Year.ToString() + DateTime.Now.ToString("MM");
        //    return strDate + fName;
        //}

        public string UploadImageContent(HttpPostedFileBase fileData)
        {
            Byte[] buffer = new Byte[1];

            string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString();
            string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString();
            string httpServer = System.Configuration.ConfigurationManager.AppSettings["HttpServer"].ToString();

            string ftpUploadUrl = string.Empty;
            string strFtpAddress = System.Configuration.ConfigurationManager.AppSettings["ftpServer"].ToString() + "Mlog/ImageContent/";

            string strName = string.Empty;
            string imgUrl = string.Empty;

            try
            {
                string folderName = DateTime.Now.Year.ToString("d4") + DateTime.Now.Month.ToString("d2");

                imgUrl = httpServer + "Mlog/ImageContent/" + folderName;

                //Create Folder
                ImageUtility.FtpCreateFolder(strFtpAddress + folderName, strUserNameFtp, strPassFtp);

                strFtpAddress = strFtpAddress + folderName;

                strName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);

                ////////
                Bitmap bmp = new Bitmap(fileData.InputStream);
                buffer = ImageUtility.SaveImage(bmp, 100L);
                ftpUploadUrl = strFtpAddress + "/" + strName;
                ImageUtility.UpFileServer(ftpUploadUrl, buffer);
                bmp.Dispose();
                ////////
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            imgUrl = imgUrl + "/" + strName;
            return imgUrl;
        }

        public string UploadUserCover(HttpPostedFileBase fileData)
        {
            Byte[] buffer = new Byte[1];

            string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString();
            string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString();

            string ftpUploadUrl = string.Empty;
            string strFtpAddress = System.Configuration.ConfigurationManager.AppSettings["ftpServer"].ToString() + "Mlog/UploadUserCover/";

            string strName = string.Empty;

            try
            {
                string folderName = DateTime.Now.Year.ToString("d4") + DateTime.Now.Month.ToString("d2");
                //Create Folder
                ImageUtility.FtpCreateFolder(strFtpAddress + folderName, strUserNameFtp, strPassFtp);

                strFtpAddress = strFtpAddress + folderName;

                strName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);

                ////////
                Bitmap bmp1000 = new Bitmap(fileData.InputStream);
                if (bmp1000.Width > 1000 || bmp1000.Height > 280)
                {
                    Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp1000, new Rectangle(0, 0, 1000, 280));
                    buffer = ImageUtility.SaveImage(bmpResize, 100L);
                    bmp1000.Dispose();
                    bmpResize.Dispose();
                }
                else buffer = ImageUtility.SaveImage(bmp1000, 100L);
                ftpUploadUrl = strFtpAddress + "/1000x280_" + strName;
                ImageUtility.UpFileServer(ftpUploadUrl, buffer);
                bmp1000.Dispose();
                ////////
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return strName;
        }
        #endregion
    }
}
